/*
 * @Author: luofeng
 * @Date: 2021-10-26 10:30:18
 * @LastEditTime: 2021-10-26 10:32:32
 * @LastEditors: luofeng
 * @Description: In User Settings Edit
 */
const NO_WECHAT_CONFIG = []
const browser = checkBrowser()
const code = getQueryVariable('code')
const queryOpenId = getQueryVariable('queryOpenId') || getQueryVariable('openId')
const path = getUrlPath()
const openId = getStore('sessionOpenId')
if (browser.weixin && !openId && !queryOpenId) {
  if (NO_WECHAT_CONFIG.includes(path)) {
    console.log('当前路由模块不需要微信授权操作')
  } else {
    if (!code) {
      // 当前c端公众号绑定域名有限，涉及到公众号开发的用当前appId对应的公众号
      const mainHost = window.location.origin
      const appId = mainHost.includes('h5-test') ? 'wx954992ea5c3d89eb' : 'wx6d7b7d1c5a5739a2'
      const router = window.location.search
      const fullPath = mainHost + window.location.pathname + router
      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(fullPath)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
      location.href = url
    }
  }
  
}

function getQueryVariable(variable) {
  const query = window.location.search.substring(1)
  const vars = query.split('&')
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=')
    if (pair[0] === variable) {
      return pair[1]
    }
  }
  return false
}

function checkBrowser() {

  if (!(window && window.navigator)) {
    return {}
  }
  const u = window.navigator.userAgent
  return {
    trident: u.indexOf('Trident') > -1, // IE内核
    presto: u.indexOf('Presto') > -1, // opera内核
    webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
    iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, // 是否iPad
    webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
    weixin: u.indexOf('MicroMessenger') > -1, // 是否微信 （2015-01-22新增）
    qq: u.match(/\sQQ/i) === ' qq', // 是否QQ
    qyweixin: u.match(/WxWork/i) === 'wxwork',
  }
}


// 获取sessionStorage
function getStore(name) {
  if (!name) {
    return
  }
  return window.sessionStorage.getItem(name)
}

function getUrlPath() {
  const path = window.location.pathname.split('?')[0]
  return path
}

